document.addEventListener('DOMContentLoaded', function() {
    // 1. 集中管理DOM元素（减少重复查询）
    const DOM = {
        cultureSelect: document.getElementById('culture'),
        quantitySlider: document.getElementById('quantity'),
        quantityDisplay: document.getElementById('quantity-display'),
        generateBtn: document.getElementById('generate-btn'),
        generateInternetBtn: document.getElementById('generate-internet-btn'),
        resetBtn: document.getElementById('reset-btn'),
        exportBtn: document.getElementById('export-btn'),
        resultsContainer: document.getElementById('results-container'),
        generatedCount: document.getElementById('generated-count'),
        resultCount: document.getElementById('result-count'),
        genderGroup: document.getElementById('gender-group'),
        typeOptions: document.querySelectorAll('.type-option'),
        showMeaningCheckbox: document.getElementById('show-meaning'),
        detailsContent: document.querySelector('.details-content'),
        allowUnisex: document.getElementById('allow-unisex'),
        featuredNames: document.querySelectorAll('.featured-name')
    };

    // 2. 初始化状态
    const initState = {
        quantity: 10,
        culture: 'random',
        gender: 'any',
        type: 'real'
    };

    // 3. 工具函数（提取公共逻辑）
    const utils = {
        // 获取选中的性别
        getSelectedGender: () => {
            return Array.from(document.getElementsByName('gender')).find(radio => radio.checked)?.value || 'any';
        },
        // 生成性别池
        getGenderPool: (selectedGender, allowUnisex) => {
            if (selectedGender === 'any') {
                const pool = ['male', 'female'];
                return allowUnisex ? [...pool, 'unisex'] : pool;
            }
            const pool = [selectedGender];
            return allowUnisex && Math.random() > 0.7 ? [...pool, 'unisex'] : pool;
        },
        // 创建姓名卡片
        createNameCard: (name, showMeaning) => {
            const card = document.createElement('div');
            card.className = `name-card ${name.type === 'internet' ? 'internet' : ''}`;
            const genderText = name.gender === 'male' ? '男' : name.gender === 'female' ? '女' : '网名';
            
            card.innerHTML = `
                <div class="name">${name.name}</div>
                <div class="origin">${getCultureName(name.origin)}</div>
                <div class="gender ${name.gender} ${name.type === 'internet' ? 'internet-tag' : ''}">${genderText}</div>
                <button class="favorite-btn"><i class="far fa-heart"></i></button>
                ${showMeaning ? `<div class="meaning">${name.meaning}</div>` : ''}
            `;

            // 绑定详情点击事件
            card.addEventListener('click', () => {
                const genderDesc = name.gender === 'male' ? '男性' : name.gender === 'female' ? '女性' : '中性';
                DOM.detailsContent.innerHTML = `
                    <div class="name-detail-header"><div class="detail-name">${name.name}</div></div>
                    <div class="detail-metadata">
                        <span><i class="fas fa-globe"></i> ${getCultureName(name.origin)}</span>
                        <span><i class="fas fa-${name.gender === 'male' ? 'mars' : name.gender === 'female' ? 'venus' : 'user'}"></i> ${genderDesc}</span>
                    </div>
                    <div class="detail-meaning"><strong>含义：</strong>${name.meaning || '暂无含义信息'}</div>
                `;
            });

            // 绑定收藏按钮事件
            card.querySelector('.favorite-btn').addEventListener('click', (e) => {
                e.stopPropagation();
                const icon = e.target.closest('i');
                icon.classList.toggle('far');
                icon.classList.toggle('fas');
            });

            return card;
        }
    };

    // 4. 核心功能函数
    // 显示姓名
    function displayNames(names, showMeaning) {
        DOM.resultsContainer.innerHTML = '';
        names.forEach(name => {
            DOM.resultsContainer.appendChild(utils.createNameCard(name, showMeaning));
        });
        // 更新计数
        const count = names.length;
        DOM.generatedCount.textContent = count;
        DOM.resultCount.textContent = `(${count})`;
    }

    // 生成真实姓名
    function generateRealNames() {
        const culture = DOM.cultureSelect.value === 'random' ? getRandomCulture() : DOM.cultureSelect.value;
        const quantity = parseInt(DOM.quantitySlider.value);
        const selectedGender = utils.getSelectedGender();
        const allowUnisex = DOM.allowUnisex.checked;
        const showMeaning = DOM.showMeaningCheckbox.checked;

        if (!nameDatabase[culture]) {
            DOM.resultsContainer.innerHTML = `<div class="empty-state"><i class="fas fa-exclamation-circle"></i><p>所选文化暂无数据</p></div>`;
            return;
        }

        const names = [];
        const cultureNames = nameDatabase[culture];

        for (let i = 0; i < quantity; i++) {
            const genderPool = utils.getGenderPool(selectedGender, allowUnisex);
            let gender = genderPool[Math.floor(Math.random() * genderPool.length)];
            let nameList = cultureNames[gender];

            //  fallback逻辑：如果当前性别无数据，尝试其他性别
            if (!nameList?.length) {
                gender = gender === 'male' ? 'female' : 'male';
                nameList = cultureNames[gender]?.length ? cultureNames[gender] : cultureNames.unisex;
            }

            if (nameList?.length) {
                const randomName = nameList[Math.floor(Math.random() * nameList.length)];
                names.push({ ...randomName, origin: culture, gender, type: 'real' });
            } else {
                DOM.resultsContainer.innerHTML = `<div class="empty-state"><i class="fas fa-exclamation-circle"></i><p>所选文化暂无数据</p></div>`;
                return;
            }
        }

        displayNames(names, showMeaning);
    }

    // 生成网名
    function generateInternetNames() {
        const quantity = parseInt(DOM.quantitySlider.value);
        const showMeaning = DOM.showMeaningCheckbox.checked;
        const nameList = nameDatabase.internet.unisex;
        const names = [];

        for (let i = 0; i < quantity; i++) {
            let randomName;
            // 避免重复（如果未超出列表长度）
            do {
                randomName = nameList[Math.floor(Math.random() * nameList.length)];
            } while (names.some(n => n.name === randomName.name) && names.length < nameList.length);

            names.push({ ...randomName, origin: 'internet', gender: 'unisex', type: 'internet' });
        }

        displayNames(names, showMeaning);
    }

    // 重置表单
    function resetForm() {
        // 重置表单值（用对象批量处理）
        const resetValues = {
            cultureSelect: 'random',
            quantitySlider: initState.quantity,
            quantityDisplay: initState.quantity,
            allowUnisex: true,
            showMeaningCheckbox: false,
            gender: 'any'
        };
        Object.entries(resetValues).forEach(([key, value]) => {
            if (key === 'gender') {
                document.querySelector(`input[name="gender"][value="${value}"]`).checked = true;
            } else {
                DOM[key].value = value;
                if (key === 'quantityDisplay') DOM[key].textContent = value;
            }
        });

        // 重置UI状态
        DOM.typeOptions.forEach(opt => opt.classList.remove('active'));
        DOM.typeOptions[0].classList.add('active');
        DOM.genderGroup.style.display = 'block';
        DOM.generateInternetBtn.style.display = 'none';
        DOM.generateBtn.style.display = 'flex';
        DOM.resultsContainer.innerHTML = `<div class="empty-state"><i class="fas fa-file-signature"></i><p>点击"生成姓名"按钮开始创建</p></div>`;
        DOM.generatedCount.textContent = '0';
        DOM.resultCount.textContent = '(0)';
        DOM.detailsContent.innerHTML = `<div class="empty-details"><i class="fas fa-hand-pointer"></i><p>点击任意名字查看详细信息</p></div>`;
    }

    // 导出结果
    function exportResults() {
        const names = Array.from(DOM.resultsContainer.querySelectorAll('.name-card')).map(card => ({
            name: card.querySelector('.name').textContent,
            origin: card.querySelector('.origin').textContent,
            gender: card.querySelector('.gender').textContent
        }));

        if (names.length === 0) {
            alert('没有可导出的姓名');
            return;
        }

        const content = "生成的姓名列表：\n\n" + names.map(n => `${n.name} | ${n.origin} | ${n.gender}`).join('\n');
        const blob = new Blob([content], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = '姓名列表.txt';
        a.click();
        URL.revokeObjectURL(url);
    }

    // 5. 事件绑定（集中管理）
    // 数量滑块更新
    DOM.quantitySlider.addEventListener('input', () => {
        DOM.quantityDisplay.textContent = DOM.quantitySlider.value;
    });

    // 切换生成类型
    DOM.typeOptions.forEach(option => {
        option.addEventListener('click', () => {
            const isInternet = option.dataset.type === 'internet';
            DOM.typeOptions.forEach(opt => opt.classList.remove('active'));
            option.classList.add('active');
            DOM.cultureSelect.value = isInternet ? 'internet' : 'random';
            DOM.genderGroup.style.display = isInternet ? 'none' : 'block';
            DOM.generateInternetBtn.style.display = isInternet ? 'flex' : 'none';
            DOM.generateBtn.style.display = isInternet ? 'none' : 'flex';
        });
    });

    // 特色姓名点击
    DOM.featuredNames.forEach(name => {
        name.addEventListener('click', () => {
            const origin = name.dataset.origin;
            const isInternet = origin === 'internet';
            // 切换类型
            DOM.typeOptions.forEach(opt => opt.classList.remove('active'));
            DOM.typeOptions[isInternet ? 1 : 0].classList.add('active');
            // 更新UI
            DOM.cultureSelect.value = origin;
            DOM.genderGroup.style.display = isInternet ? 'none' : 'block';
            DOM.generateInternetBtn.style.display = isInternet ? 'flex' : 'none';
            DOM.generateBtn.style.display = isInternet ? 'none' : 'flex';
            // 生成对应姓名
            isInternet ? generateInternetNames() : generateRealNames();
        });
    });

    // 显示含义切换
    DOM.showMeaningCheckbox.addEventListener('change', () => {
        const cards = Array.from(DOM.resultsContainer.querySelectorAll('.name-card'));
        if (cards.length) {
            const names = cards.map(card => ({
                name: card.querySelector('.name').textContent,
                meaning: card.querySelector('.meaning')?.textContent || '',
                origin: card.querySelector('.origin').textContent,
                gender: card.querySelector('.gender').classList.contains('male') ? 'male' : 
                        card.querySelector('.gender').classList.contains('female') ? 'female' : 'unisex',
                type: card.classList.contains('internet') ? 'internet' : 'real'
            }));
            displayNames(names, DOM.showMeaningCheckbox.checked);
        }
    });

    // 绑定核心按钮事件
    DOM.generateBtn.addEventListener('click', generateRealNames);
    DOM.generateInternetBtn.addEventListener('click', generateInternetNames);
    DOM.resetBtn.addEventListener('click', resetForm);
    DOM.exportBtn.addEventListener('click', exportResults);

    // 初始化
    DOM.generateInternetBtn.style.display = 'none';
    generateRealNames();
});